﻿using System.Net;
using System.Text;
using System.Web;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace ApiLib.Utils;

/// <summary>
/// HTTP工具类
/// </summary>
public static class HttpUtil
{
    static HttpUtil()
    {
        ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
        ServicePointManager.SecurityProtocol =
            SecurityProtocolType.Tls |
            SecurityProtocolType.Tls11 |
            SecurityProtocolType.Tls12 |
            SecurityProtocolType.Tls13;
    }

    private static readonly HttpClientHandler ClientHandler = new()
    {
        AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
        AllowAutoRedirect = true,
        UseCookies = true,
        ServerCertificateCustomValidationCallback = (_, _, _, _) => true
    };

    /// <summary>
    /// http客户端
    /// </summary>
    public static readonly HttpClient Client = new(ClientHandler) { Timeout = TimeSpan.FromMinutes(10) };

    /// <summary>
    /// 新的HttpClient
    /// </summary>
    /// <param name="autoRedirect">自动重定向</param>
    /// <param name="useCookies">使用cookie</param>
    /// <param name="sslCallback">ssl证书</param>
    /// <param name="timeoutMinutes">超时（分钟）</param>
    /// <returns></returns>
    public static HttpClient Builder(bool autoRedirect = true, bool useCookies = true, bool sslCallback = true,
        int timeoutMinutes = 10)
    {
        return new(new HttpClientHandler()
        {
            AllowAutoRedirect = autoRedirect,
            UseCookies = useCookies,
            ServerCertificateCustomValidationCallback = (_, _, _, _) => sslCallback
        }) { Timeout = TimeSpan.FromMinutes(timeoutMinutes) };
    }

    /// <summary>
    /// 新的HttpClient
    /// </summary>
    /// <param name="handler">处理器</param>
    /// <param name="timeoutMinutes">超时（分钟）</param>
    /// <returns></returns>
    public static HttpClient Builder(HttpClientHandler handler, int timeoutMinutes = 10)
    {
        return new(handler) { Timeout = TimeSpan.FromMinutes(timeoutMinutes) };
    }

    /// <summary>
    /// 上传
    /// </summary>
    /// <param name="url"></param>
    /// <param name="file"></param>
    /// <param name="headers"></param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static async Task<T?> UploadAsync<T>(string url, IBrowserFile file,
        Dictionary<string, string>? headers = null)
    {
        var message = GetRequestMessage(HttpMethod.Post, url, headers);
        using var content = new MultipartFormDataContent();
        const long maxfilesize = 100 * 1024 * 1024;
        var fileContent = new StreamContent(file.OpenReadStream(maxfilesize));
        content.Add(fileContent, "file", HttpUtility.UrlEncode(file.Name));
        message.Content = content;
        return await SendRequestAsync<T>(message);
    }

    /// <summary>
    /// 下载文件
    /// </summary>
    /// <param name="url"></param>
    /// <param name="body"></param>
    /// <param name="headers"></param>
    /// <param name="isPost"></param>
    /// <returns></returns>
    public static Stream? Download(string url, Dictionary<string, string>? headers = null,
        bool isPost = false, object? body = null)
    {
        var message = GetRequestMessage(isPost ? HttpMethod.Post : HttpMethod.Get, url, headers);
        if (isPost)
        {
            message.Content = new StringContent(body.Serialize(), Encoding.UTF8, "application/json");
        }

        try
        {
            var responseMessage = Client.Send(message);
            return responseMessage.Content.ReadAsStream();
        }
        catch (HttpRequestException e)
        {
            e.Message.LogError();
            return default;
        }
    }

    /// <summary>
    /// 下载文件
    /// </summary>
    /// <param name="url"></param>
    /// <param name="body"></param>
    /// <param name="headers"></param>
    /// <param name="isPost"></param>
    /// <returns></returns>
    public static async Task<Stream?> DownloadAsync(string url, Dictionary<string, string>? headers = null,
        bool isPost = false, object? body = null)
    {
        var message = GetRequestMessage(isPost ? HttpMethod.Post : HttpMethod.Get, url, headers);
        if (isPost)
        {
            message.Content = new StringContent(body.Serialize(), Encoding.UTF8, "application/json");
        }

        try
        {
            var responseMessage = await Client.SendAsync(message);
            return await responseMessage.Content.ReadAsStreamAsync();
        }
        catch (HttpRequestException e)
        {
            e.Message.LogError();
            return default;
        }
    }

    /// <summary>
    /// 下载文件
    /// </summary>
    /// <param name="url"></param>
    /// <param name="body"></param>
    /// <param name="headers"></param>
    /// <param name="isPost"></param>
    /// <returns></returns>
    public static async Task<byte[]?> DownloadByteAsync(string url, Dictionary<string, string>? headers = null,
        bool isPost = false, object? body = null)
    {
        var message = GetRequestMessage(isPost ? HttpMethod.Post : HttpMethod.Get, url, headers);
        if (isPost)
        {
            message.Content = new StringContent(body.Serialize(), Encoding.UTF8, "application/json");
        }

        try
        {
            var responseMessage = await Client.SendAsync(message);
            return await responseMessage.Content.ReadAsByteArrayAsync();
        }
        catch (HttpRequestException e)
        {
            e.Message.LogError();
            return default;
        }
    }

    /// <summary>
    /// GET请求
    /// </summary>
    /// <param name="url">地址</param>
    /// <param name="headers">请求头</param>
    /// <returns></returns>
    public static HttpResult HttpGet(string url, Dictionary<string, string>? headers = null)
    {
        var message = GetRequestMessage(HttpMethod.Get, url, headers);
        return SendRequest(message);
    }

    /// <summary>
    /// GET请求
    /// </summary>
    /// <param name="url">地址</param>
    /// <param name="headers">请求头</param>
    /// <returns></returns>
    public static async Task<HttpResult> HttpGetAsync(string url, Dictionary<string, string>? headers = null)
    {
        var message = GetRequestMessage(HttpMethod.Get, url, headers);
        return await SendRequestAsync(message);
    }

    /// <summary>
    /// GET请求
    /// </summary>
    /// <param name="url">地址</param>
    /// <param name="headers">请求头</param>
    /// <returns></returns>
    public static T? HttpGet<T>(string url, Dictionary<string, string>? headers = null)
    {
        var message = GetRequestMessage(HttpMethod.Get, url, headers);
        return SendRequest<T>(message);
    }

    /// <summary>
    /// GET请求
    /// </summary>
    /// <param name="url">地址</param>
    /// <param name="headers">请求头</param>
    /// <returns></returns>
    public static async Task<T?> HttpGetAsync<T>(string url, Dictionary<string, string>? headers = null)
    {
        var message = GetRequestMessage(HttpMethod.Get, url, headers);
        return await SendRequestAsync<T>(message);
    }

    /// <summary>
    /// Delete请求
    /// </summary>
    /// <param name="url">地址</param>
    /// <param name="headers">请求头</param>
    /// <returns></returns>
    public static HttpResult HttpDelete(string url, Dictionary<string, string>? headers = null)
    {
        var message = GetRequestMessage(HttpMethod.Delete, url, headers);
        return SendRequest(message);
    }

    /// <summary>
    /// Delete请求
    /// </summary>
    /// <param name="url">地址</param>
    /// <param name="headers">请求头</param>
    /// <returns></returns>
    public static async Task<HttpResult> HttpDeleteAsync(string url, Dictionary<string, string>? headers = null)
    {
        var message = GetRequestMessage(HttpMethod.Delete, url, headers);
        return await SendRequestAsync(message);
    }

    /// <summary>
    /// Delete请求
    /// </summary>
    /// <param name="url">地址</param>
    /// <param name="headers">请求头</param>
    /// <returns></returns>
    public static T? HttpDelete<T>(string url, Dictionary<string, string>? headers = null)
    {
        var message = GetRequestMessage(HttpMethod.Delete, url, headers);
        return SendRequest<T>(message);
    }

    /// <summary>
    /// Delete请求
    /// </summary>
    /// <param name="url">地址</param>
    /// <param name="headers">请求头</param>
    /// <returns></returns>
    public static async Task<T?> HttpDeleteAsync<T>(string url, Dictionary<string, string>? headers = null)
    {
        var message = GetRequestMessage(HttpMethod.Delete, url, headers);
        return await SendRequestAsync<T>(message);
    }

    /// <summary>
    /// POST请求
    /// </summary>
    /// <param name="url">地址</param>
    /// <param name="headers">请求头</param>
    /// <param name="body">内容</param>
    /// <param name="type">请求体类型</param>
    /// <returns></returns>
    public static HttpResult HttpPost(string url, Dictionary<string, string>? headers = null,
        object? body = null, HttpContentType type = HttpContentType.Json)
    {
        var message = GetRequestMessage(HttpMethod.Post, url, headers, body, type);
        // message.Content = new StringContent(body.Serialize(), Encoding.UTF8, type.GetString());
        // message.BuildContent(body, type);
        return SendRequest(message);
    }

    /// <summary>
    /// POST请求
    /// </summary>
    /// <param name="url">地址</param>
    /// <param name="headers">请求头</param>
    /// <param name="body">内容</param>
    /// <param name="type">请求体类型</param>
    /// <returns></returns>
    public static async Task<HttpResult> HttpPostAsync(string url, Dictionary<string, string>? headers = null,
        object? body = null, HttpContentType type = HttpContentType.Json)
    {
        var message = GetRequestMessage(HttpMethod.Post, url, headers, body, type);
        // message.Content = new StringContent(body.Serialize(), Encoding.UTF8, type.GetString());
        // message.BuildContent(body, type);
        return await SendRequestAsync(message);
    }

    /// <summary>
    /// POST请求
    /// </summary>
    /// <param name="url">地址</param>
    /// <param name="headers">请求头</param>
    /// <param name="body">内容</param>
    /// <param name="type">请求体类型</param>
    /// <returns></returns>
    public static T? HttpPost<T>(string url, Dictionary<string, string>? headers = null,
        object? body = null, HttpContentType type = HttpContentType.Json)
    {
        var message = GetRequestMessage(HttpMethod.Post, url, headers, body, type);
        // message.Content = new StringContent(body.Serialize(), Encoding.UTF8, type.GetString());
        // message.BuildContent(body, type);
        return SendRequest<T>(message);
    }

    /// <summary>
    /// POST请求
    /// </summary>
    /// <param name="url">地址</param>
    /// <param name="headers">请求头</param>
    /// <param name="body">内容</param>
    /// <param name="type">请求体类型</param>
    /// <returns></returns>
    public static async Task<T?> HttpPostAsync<T>(string url, Dictionary<string, string>? headers = null,
        object? body = null, HttpContentType type = HttpContentType.Json)
    {
        var message = GetRequestMessage(HttpMethod.Post, url, headers, body, type);
        // message.Content = new StringContent(body.Serialize(), Encoding.UTF8, type.GetString());
        // message.BuildContent(body, type);
        return await SendRequestAsync<T>(message);
    }


    /// <summary>
    /// POST请求，表单提交，文件上传
    /// </summary>
    /// <param name="url">地址</param>
    /// <param name="headers"></param>
    /// <param name="body">内容</param>
    /// <returns></returns>
    public static T? PostForm<T>(string url, Dictionary<string, string>? headers = null,
        MultipartFormDataContent? body = null)
    {
        var message = GetRequestMessage(HttpMethod.Post, url, headers);
        message.Content = body;
        return SendRequest<T>(message);
    }

    /// <summary>
    /// POST请求，表单提交，文件上传
    /// </summary>
    /// <param name="url">地址</param>
    /// <param name="headers"></param>
    /// <param name="body">内容</param>
    /// <returns></returns>
    public static async Task<T?> PostFormAsync<T>(string url, Dictionary<string, string>? headers = null,
        MultipartFormDataContent? body = null)
    {
        var message = GetRequestMessage(HttpMethod.Post, url, headers);
        message.Content = body;
        return await SendRequestAsync<T>(message);
    }

    /// <summary>
    /// POST请求，表单提交，文件上传
    /// </summary>
    /// <param name="url">地址</param>
    /// <param name="headers"></param>
    /// <param name="body">内容</param>
    /// <returns></returns>
    public static HttpResult PostForm(string url, Dictionary<string, string>? headers = null,
        MultipartFormDataContent? body = null)
    {
        var message = GetRequestMessage(HttpMethod.Post, url, headers);
        message.Content = body;
        return SendRequest(message);
    }

    /// <summary>
    /// POST请求，表单提交，文件上传
    /// </summary>
    /// <param name="url">地址</param>
    /// <param name="headers"></param>
    /// <param name="body">内容</param>
    /// <returns></returns>
    public static async Task<HttpResult> PostFormAsync(string url, Dictionary<string, string>? headers = null,
        MultipartFormDataContent? body = null)
    {
        var message = GetRequestMessage(HttpMethod.Post, url, headers);
        message.Content = body;
        return await SendRequestAsync(message);
    }

    /// <summary>
    /// 发送请求
    /// </summary>
    /// <param name="message"></param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    private static T? SendRequest<T>(HttpRequestMessage message)
    {
        try
        {
            var responseMessage = Client.Send(message);
            if (responseMessage.IsSuccessStatusCode)
            {
                var result = responseMessage.Content.ReadAsStringAsync().Result;
                WebUtil.LogInfo("云MAS短信发送：" + result);
                return result.Deserialize<T>();
            }
        }
        catch (HttpRequestException e)
        {
            e.Message.LogError();
        }

        return default;
    }

    /// <summary>
    /// 发送请求
    /// </summary>
    /// <param name="message"></param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    private static async Task<T?> SendRequestAsync<T>(HttpRequestMessage message)
    {
        try
        {
            var responseMessage = await Client.SendAsync(message);
            if (responseMessage.IsSuccessStatusCode)
            {
                var result = await responseMessage.Content.ReadAsStringAsync();
                return result.Deserialize<T>();
            }
        }
        catch (HttpRequestException e)
        {
            e.Message.LogError();
        }

        return default;
    }

    /// <summary>
    /// 发送请求
    /// </summary>
    /// <param name="message"></param>
    /// <returns></returns>
    private static HttpResult SendRequest(HttpRequestMessage message)
    {
        try
        {
            var responseMessage = Client.Send(message);
            return new HttpResult
            {
                Code = (int)responseMessage.StatusCode,
                Message = responseMessage.StatusCode.ToString(),
                Content = responseMessage.Content.ReadAsStringAsync().Result
            };
        }
        catch (HttpRequestException e)
        {
            e.Message.LogError();
            return new HttpResult { Code = 500, Message = e.Message };
        }
    }

    /// <summary>
    /// 发送请求
    /// </summary>
    /// <param name="message"></param>
    /// <returns></returns>
    private static async Task<HttpResult> SendRequestAsync(HttpRequestMessage message)
    {
        try
        {
            var responseMessage = await Client.SendAsync(message);
            return new HttpResult
            {
                Code = (int)responseMessage.StatusCode,
                Message = responseMessage.StatusCode.ToString(),
                Content = await responseMessage.Content.ReadAsStringAsync()
            };
        }
        catch (HttpRequestException e)
        {
            e.Message.LogError();
            return new HttpResult { Code = 500, Message = e.Message };
        }
    }

    /// <summary>
    /// 获取请求信息
    /// </summary>
    /// <param name="method">请求方法</param>
    /// <param name="url">地址</param>
    /// <param name="headers">请求头</param>
    /// <param name="body">内容</param>
    /// <param name="type">内容格式</param>
    /// <returns></returns>
    public static HttpRequestMessage GetRequestMessage(HttpMethod method, string url,
        Dictionary<string, string>? headers = null, object? body = null,
        HttpContentType type = HttpContentType.Json)
    {
        ServicePointManager.SecurityProtocol =
            SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
        var message = new HttpRequestMessage(method, url);
        if (headers is { Count: > 0 })
        {
            foreach (var (key, value) in headers)
            {
                message.Headers.Add(key, value);
            }
        }

        if (body != null)
        {
            message.BuildContent(body, type);
        }

        return message;
    }


    /// <summary>
    /// 获取HttpContentType字符串
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public static string GetString(this HttpContentType type)
    {
        return type switch
        {
            HttpContentType.Text => HttpContentTypeString.Text,
            HttpContentType.Stream => HttpContentTypeString.Stream,
            HttpContentType.Form => HttpContentTypeString.Form,
            HttpContentType.MultipartForm => HttpContentTypeString.MultipartForm,
            _ => HttpContentTypeString.Json
        };
    }

    /// <summary>
    /// HttpContentType字符串
    /// </summary>
    private static class HttpContentTypeString
    {
        /// <summary>
        /// 普通文本
        /// </summary>
        public const string Text = "text/plain";

        /// <summary>
        /// JSON字符串
        /// </summary>
        public const string Json = "application/json";

        /// <summary>
        /// 数据流类型(文件流)
        /// </summary>
        public const string Stream = "application/octet-stream";

        /// <summary>
        /// 表单数据(键值对)
        /// </summary>
        public const string Form = "application/x-www-form-urlencoded";

        /// <summary>
        /// 多分部数据
        /// </summary>
        public const string MultipartForm = "multipart/form-data";
    }
}

/// <summary>
/// HttpUtilExtend
/// </summary>
public static class HttpUtilExtend
{
    private static readonly HttpClient Client = new() { Timeout = TimeSpan.FromSeconds(30) };

    /// <summary>
    /// 发起Http请求
    /// </summary>
    /// <param name="url">地址</param>
    /// <param name="headers">头部</param>
    /// <typeparam name="T">类型</typeparam>
    /// <returns></returns>
    public static T? HttpGet<T>(this string url, Dictionary<string, string>? headers = null)
    {
        return HttpUtil.HttpGet<T>(url, headers);
    }

    /// <summary>
    /// 发起Http请求
    /// </summary>
    /// <param name="url">地址</param>
    /// <param name="headers">头部</param>
    /// <param name="body">请求体</param>
    /// <param name="type">请求类型</param>
    /// <typeparam name="T">类型</typeparam>
    /// <returns></returns>
    public static T? HttpPost<T>(this string url, Dictionary<string, string>? headers = null,
        object? body = null, HttpContentType type = HttpContentType.Json)
    {
        return HttpUtil.HttpPost<T>(url, headers, body, type);
    }

    /// <summary>
    /// Build内容
    /// </summary>
    /// <param name="message"></param>
    /// <param name="body"></param>
    /// <param name="type"></param>
    public static void BuildContent(this HttpRequestMessage message, object? body = null,
        HttpContentType type = HttpContentType.Json)
    {
        var content = "";
        if (type == HttpContentType.Form)
        {
            if (body != null)
            {
                var dictionary = body.ToDictionary();
                foreach (var pair in dictionary)
                {
                    if (content != "")
                    {
                        content += "&";
                    }

                    content += pair.Key + "=" + (pair.Value?.ToString() ?? "");
                }
            }
        }
        else
        {
            content = body.Serialize();
        }

        message.Content = new StringContent(content, Encoding.UTF8, type.GetString());
    }

    /// <summary>
    /// 转发
    /// </summary>
    /// <param name="request"></param>
    /// <param name="newUrl"></param>
    /// <returns></returns>
    public static async Task<HttpResponseMessage> Forward(this HttpRequest request, string newUrl)
    {
        var httpMethod = new HttpMethod(request.Method);
        var message = new HttpRequestMessage(httpMethod, newUrl + request.QueryString);
        if (request.Headers is { Count: > 0 })
        {
            foreach (var (key, value) in request.Headers)
            {
                if (!string.IsNullOrEmpty(key) && !key.Contains(":"))
                {
                    try
                    {
                        message.Headers.Add(key, value.ToString());
                    }
                    catch (Exception)
                    {
                        // ignored
                    }
                }
            }
        }

        if (request.ContentType != null)
        {
            if (request.ContentType.Contains(HttpContentType.MultipartForm.GetString()))
            {
                var formContent = new List<KeyValuePair<string, string>>();
                foreach (var key in request.Form.Keys)
                {
                    formContent.Add(new KeyValuePair<string, string>(key, request.Form[key]));
                }

                var multipartContent = new FormUrlEncodedContent(formContent);
                var httpContent = new MultipartFormDataContent();
                httpContent.Add(multipartContent);
                foreach (var file in request.Form.Files)
                {
                    httpContent.Add(new StreamContent(file.OpenReadStream()), file.Name,
                        HttpUtility.UrlEncode(file.FileName));
                }

                message.Content = httpContent;
            }
            else
            {
                //处理body数据
                using MemoryStream memoryStream = new();
                // 复制Body数据到缓存
                await request.Body.CopyToAsync(memoryStream);
                memoryStream.Position = 0;
                using StreamReader streamReader = new(memoryStream);
                // 读取Body数据
                var body = await streamReader.ReadToEndAsync();
                message.Content = new StringContent(body, Encoding.UTF8, "application/json");
                if (message.Content.Headers.ContentType != null)
                {
                    message.Content.Headers.ContentType.CharSet = "utf-8";
                }
            }
        }

        return await Client.SendAsync(message);
    }

    /// <summary>
    /// 转发
    /// </summary>
    /// <param name="context">请求上下文</param>
    /// <param name="newUrl">转发完整地址</param>
    /// <returns></returns>
    public static async Task Forward(this HttpContext context, string newUrl)
    {
        var response = await context.Request.Forward(newUrl);
        foreach (var (key, value) in response.Content.Headers)
        {
            context.Response.Headers.Add(key, value.First());
        }

        context.Response.StatusCode = (int)response.StatusCode;
        await response.Content.CopyToAsync(context.Response.Body);
    }

    /// <summary>
    /// 转发
    /// </summary>
    /// <param name="context">请求上下文</param>
    /// <param name="response"></param>
    /// <returns></returns>
    public static async Task CopyFrom(this HttpContext context, HttpResponseMessage? response)
    {
        if (response == null)
        {
            return;
        }

        foreach (var (key, value) in response.Content.Headers)
        {
            context.Response.Headers.Append(key, value.First());
        }

        context.Response.StatusCode = (int)response.StatusCode;
        await response.Content.CopyToAsync(context.Response.Body);
    }

    /// <summary>
    /// 发送请求
    /// </summary>
    /// <param name="client"></param>
    /// <param name="message"></param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static T? SendRequest<T>(this HttpClient client, HttpRequestMessage message)
    {
        try
        {
            var responseMessage = client.Send(message);
            if (responseMessage.IsSuccessStatusCode)
            {
                var result = responseMessage.Content.ReadAsStringAsync().Result;
                return result.Deserialize<T>();
            }
        }
        catch (Exception e)
        {
            WebUtil.Error("请求异常", e);
            // e.Message.LogError();
        }

        return default;
    }


    /// <summary>
    /// 转发
    /// </summary>
    /// <param name="context"></param>
    /// <param name="targetUrl">目标URL</param>
    /// <param name="httpClient">自定义客户端</param>
    /// <param name="respHeader">返回响应头</param>
    /// <param name="clearHeader">清除请求头</param>
    /// <param name="reqHeaders">自定义请求头</param>
    public static async Task ToForward(this HttpContext context, string targetUrl, HttpClient? httpClient = null,
        bool clearHeader = false, bool respHeader = true, Dictionary<string, string>? reqHeaders = null)
    {
        // 使用IHttpClientFactory来获取HttpClient实例
        var client = httpClient ?? context.RequestServices.GetRequiredService<IHttpClientFactory>().CreateClient();

        // 转发请求头
        var requestMessage = new HttpRequestMessage(new HttpMethod(context.Request.Method), targetUrl);
        foreach (var header in context.Request.Headers)
        {
            requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
        }

        //清除请求头
        if (clearHeader)
        {
            requestMessage.Headers.Clear();
        }

        //自定义请求头
        if (reqHeaders != null)
        {
            foreach (var (key, value) in reqHeaders)
            {
                requestMessage.Headers.TryAddWithoutValidation(key, value);
            }
        }

        // 如果是POST/PUT等方法，还需要转发请求体
        if (context.Request.Method is "POST" or "PUT" && context.Request.Body.CanRead)
        {
            context.Request.Body.Position = 0; // 确保从开始读取
            requestMessage.Content = new StreamContent(context.Request.Body);
        }

        // 发送请求到目标服务器并获取响应
        var response = await client.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead,
            context.RequestAborted);

        // 将响应状态码和头信息复制回客户端
        context.Response.StatusCode = (int)response.StatusCode;

        var allowedHeaders = new[]
        {
            "Content-Type", "Content-Encoding", "Content-Length", "Cache-Control", "Expires", "Date", "Server"
        };

        if (respHeader)
        {
            foreach (var header in response.Headers)
            {
                if (allowedHeaders.Contains(header.Key))
                {
                    context.Response.Headers[header.Key] = header.Value.ToArray();
                }
            }
        }

        foreach (var header in response.Content.Headers)
        {
            if (allowedHeaders.Contains(header.Key))
            {
                context.Response.Headers[header.Key] = header.Value.ToArray();
            }
        }

        // 将响应内容复制回客户端
        await response.Content.CopyToAsync(context.Response.Body);
    }
}

/// <summary>
/// HTTP请求结果
/// </summary>
public class HttpResult
{
    /// <summary>
    /// 状态码
    /// </summary>
    public int Code { get; init; }

    /// <summary>
    /// 信息
    /// </summary>
    public string Message { get; init; } = "";

    /// <summary>
    /// 内容
    /// </summary>
    public string Content { get; init; } = "";

    /// <summary>
    /// 打印
    /// </summary>
    /// <returns></returns>
    public override string ToString()
    {
        return "[code:" + Code + ",\r\nMessage:" + Message + ",\r\nContent:" + Content + "]";
    }

    /// <summary>
    /// 请求是否成功
    /// </summary>
    public bool IsSuccess => Code == 200;
}

/// <summary>
/// HttpContent类型
/// </summary>
public enum HttpContentType
{
    /// <summary>
    /// 文本
    /// </summary>
    Text,

    /// <summary>
    /// JSON
    /// </summary>
    Json,

    /// <summary>
    /// 流
    /// </summary>
    Stream,

    /// <summary>
    /// 表格
    /// </summary>
    Form,

    /// <summary>
    /// 文件
    /// </summary>
    MultipartForm
}